package com.banzhi.shop.activity;


import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Temai.Temai_data;

import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.fragment.TeMaiFrg;
import com.banzhi.shop.model.CallBack.HomeFrgModelCallBack;
import com.banzhi.shop.model.CallBack.ISCanByCallBack;
import com.banzhi.shop.model.CallBack.TemaiFrgCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;
import com.banzhi.shop.model.IHomeFrgModel;
import com.banzhi.shop.model.IIsCanByModel;
import com.banzhi.shop.model.ITemaiFrgModel;
import com.banzhi.shop.model.Impl.HomeFrgModelImpl;
import com.banzhi.shop.model.Impl.IsCanByImpl;
import com.banzhi.shop.model.Impl.TemaiFrgImpl;
import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.CustomToast;
import com.banzhi.shop.utils.DateUtil;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TemaiActivity extends BaseActivity implements TemaiFrgCallBack, SwipeRefreshLayout.OnRefreshListener, HomeFrgModelCallBack, ISCanByCallBack, WXshareCallBack {


    private ITemaiFrgModel model;
    private IIsCanByModel canByModel;
    private int position;
    private SwipeRefreshLayout srllistview;
    /**
     * 特卖商品实体类集合
     */
    private List<Temai_data> temaidata = new ArrayList<>();
    private Timer timer;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }
    };
    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private WXshareModel wxmodel;
    private int pos;

    private int page = 1;
    private RelativeLayout rlnodata;
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private CommonHeadAdapter<Temai_data> adapter;
    private IHomeFrgModel homemodel;
    /**
     * 时候以添加到店铺的状态值
     */
    private String icon;
    private ImageView mIvBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temai);
        Translucent.setTranslucent(this);
        initView();
        setListeners();
        model = new TemaiFrgImpl();
        model.getData(page, this);
        wxmodel = new WXshareImpl();
        homemodel = new HomeFrgModelImpl();
        canByModel = new IsCanByImpl();
    }

    private void setListeners() {
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                model.getData(page, TemaiActivity.this);
            }
        });

    }

    private void initView() {
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        srllistview = (SwipeRefreshLayout)findViewById(R.id.srl_listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srllistview.setOnRefreshListener(this);
        rlnodata = (RelativeLayout)findViewById(R.id.rl_nodata);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);

    }
    //特卖
    @Override
    public void ongetDataSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        if (page == 1) {
            temaidata.clear();
        } else {
            if (((List<Temai_data>) object).size() == 0) {
                return;
            }
        }
        temaidata.addAll((List<Temai_data>) object);

        if (temaidata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        initData();
        LoadingDialogUtils.dismiss();
    }

    private void initData() {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        if (adapter == null) {
            adapter = new CommonHeadAdapter<Temai_data>(TemaiActivity.this, R.layout.item_temai, temaidata) {
                @Override
                public void convert(ViewHolder holder, final Temai_data data, final int position) {
                    if (data.getImages() != null && ASUtils.isCanUse(data.getImages()[0])) {
                        Picasso.with(MyApp.context).load(data.getThumb()).placeholder(R.mipmap.zhanweitu2).into(holder.getImageView(R.id.iv_image));
                    }
                    if ("0".equals(data.getTotal())) {
                        holder.getView(R.id.img_sold_out).setVisibility(View.VISIBLE);
                    }

                    holder.setText(R.id.tv_title, data.getTitle());
                    if (System.currentTimeMillis() / 1000 < Long.parseLong(data.getTimestart())) {
                        holder.setText(R.id.tv_statu, "距离开始");
                        Long time = Long.parseLong(data.getTimestart()) - System.currentTimeMillis() / 1000;
                        holder.setText(R.id.tv_time, DateUtil.getDaoJiShiTimeUnixs(time));
                    } else if (System.currentTimeMillis() / 1000 > Long.parseLong(data.getTimestart()) && System.currentTimeMillis() / 1000 < Long.parseLong(data.getTimeend())) {
                        holder.setText(R.id.tv_statu, "距离结束");
                        Long time = Long.parseLong(data.getTimeend()) - System.currentTimeMillis() / 1000;
                        holder.setText(R.id.tv_time, DateUtil.getDaoJiShiTimeUnixs(time));
                    } else {
                        holder.setText(R.id.tv_statu, "活动已过期");
                        holder.getView(R.id.tv_time).setVisibility(View.GONE);
                    }
                    holder.getImageView(R.id.iv_fenxiang).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            wxURL = null;
                           TemaiActivity.this.pos = position;
                            showSharePopupwindow(data);
                        }
                    });
                    //素材
                    holder.getImageView(R.id.iv_add_image).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                       /*     canByModel.getData(temaidata.get(position).getGoods_id(),TemaiActivity.this);
                           TemaiActivity.this.pos = position;*/

                            Intent intent = new Intent(TemaiActivity.this, CommodityDetailsActivity.class);
                            intent.putExtra("id", data.getGoods_id());
                            intent.putExtra("type", "1");
                            startActivity(intent);
                        }
                    });
                    if ("0".equals(data.getIcon())) {
                        holder.getImageView(R.id.iv_add_dianpu).setImageResource(R.mipmap.jian1);

                        holder.getImageView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                                homemodel.deleteGoods(data.getGoods_id(), null,TemaiActivity.this);
                               TemaiActivity.this.pos = position;
                               TemaiActivity.this.icon = data.getIcon();
                            }
                        });
                    } else if ("1".equals(data.getIcon())) {
                        holder.getImageView(R.id.iv_add_dianpu).setImageResource(R.mipmap.jia1);
                        holder.getImageView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                                homemodel.AddDianpu(data.getGoods_id(), TemaiActivity.this);
                                TemaiActivity.this.pos = position;
                                TemaiActivity.this.icon = data.getIcon();
                            }
                        });
                    }
                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setOnItemClickListener(new CommonHeadAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                canByModel.getData(temaidata.get(position).getGoods_id(), TemaiActivity.this);
                TemaiActivity.this.position = position;

            }
        });

        if (timer == null) {
            timer = new Timer();
        } else {
            timer.cancel();
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                handler.sendMessage(msg);
            }
        }, 0, 999);

    }

    private void showSharePopupwindow(final Temai_data data) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_share_dianzhu, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失

        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        if (data != null) {
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getGoods_id(), null, LIANJIE, TemaiActivity.this);
                    } else {
                        ShareUtils.copyLianjie(TemaiActivity.this, wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getGoods_id(), null, WEIXINHAOYOU, TemaiActivity.this);
                    } else {
                        ShareUtils.wxshare(data.getTitle(), data.getImages()[0], "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                        Log.d("vmvkmvkdfmfvkdfvmdf", data.getGoods_id());
                        wxmodel.getData(data.getGoods_id(), null, PENGYOUQUAN, TemaiActivity.this);
                    } else {
                        ShareUtils.wxPengyouquan(data.getTitle(), data.getImages()[0], wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(TemaiActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getGoods_id(), null, ERWEIMA, TemaiActivity.this);
                    } else {
                        ShareUtils.ereima3(TemaiActivity.this, data.getTitle(), data.getMarketprice(), null, null, null, data.getImages()[0], wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void ongetDataError(Object object) {
        LoadingDialogUtils.dismiss();
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();
    }

    @Override
    public void onRefresh() {
        page = 1;
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);
    }

    @Override
    public void getDataSuccess(Object object) {
        Intent intent = new Intent(this, CommodityDetailsActivity.class);
        intent.putExtra("id", temaidata.get(position).getGoods_id());
        startActivity(intent);
    }

    @Override
    public void getDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void AddDianpuSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "上架成功", jsonObject.optString("res"));
//        ToastUtils.makeToastShort("添加到店铺成功");
        if ("0".equals(icon)) {
            temaidata.get(pos).setIcon("1");
        } else {
            temaidata.get(pos).setIcon("0");
        }
        adapter.notifyItemChanged(pos);
    }

    @Override
    public void AddDianpuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void deleteSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "下架成功", jsonObject.optString("res"));
        if ("0".equals(icon)) {
            temaidata.get(pos).setIcon("1");
        } else {
            temaidata.get(pos).setIcon("0");
        }
        adapter.notifyItemChanged(pos);
    }

    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void getCanBuySuccess(Object object) {
        Intent intent = new Intent(this, CommodityDetailsActivity.class);
        intent.putExtra("id", temaidata.get(position).getGoods_id());
        startActivity(intent);
    }

    @Override
    public void getCanBuyError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(this, wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima3(this, temaidata.get(pos).getTitle(), temaidata.get(pos).getMarketprice(), null, null, null, temaidata.get(pos).getImages()[0], wxURL);
        } else if (num == WEIXINHAOYOU) {
            ShareUtils.wxshare(temaidata.get(pos).getTitle(), temaidata.get(pos).getImages()[0], "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(temaidata.get(pos).getTitle(), temaidata.get(pos).getImages()[0], wxURL);
        }
    }

    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }
}
